using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using JoyfulHomeJourney.BackEnd.Infrastructure.Atrributes;
using JoyfulHomeJourney.BackEnd.Infrastructure.Dtos.Requests.Objects;
using JoyfulHomeJourney.BackEnd.Infrastructure.Dtos.Responses;
using JoyfulHomeJourney.BackEnd.Infrastructure.Dtos.Responses.Objects;
using JoyfulHomeJourney.BackEnd.Infrastructure.EFCore;
using JoyfulHomeJourney.BackEnd.Infrastructure.Tools;
using JoyfulHomeJourney.BackEnd.Server.EFCore;
using JoyfulHomeJourney.BackEnd.Server.Instances.Extends.Requests;
using JoyfulHomeJourney.BackEnd.Server.Instances.Extends.Responses;
using JoyfulHomeJourney.BackEnd.Server.Interfaces;
using Microsoft.EntityFrameworkCore;
namespace JoyfulHomeJourney.BackEnd.Server.Instances
{
    /// <summary>
    /// 一个类包含了服务类所需的所有仓库表的实例，仅提供给该服务类使用，请将所有服务类所需的仓库表的实例都放在该类中。
    /// 仓库表的实例指提供了操作数据库指定表的所有方法的对象
    /// </summary>
    internal class SysCarShopsEF
    {
        public SysCarShopsEF(DbContext dbContext)
        {
            sysCarShopsServerEF = new SysCarShopsServerEF(dbContext);
            dictionarysServerEF = new DictionarysServerEF(dbContext);
            sysAccountsServerEF = new SysAccountsServerEF(dbContext);
            sysProductsServerEF = new SysProductsServerEF(dbContext);
            employeesServerEF = new EmployeesServerEF(dbContext);
        }
        public SysCarShopsServerEF sysCarShopsServerEF { get; set; }
        public DictionarysServerEF dictionarysServerEF { get; set; }
        public SysAccountsServerEF sysAccountsServerEF { get; set; }
        public SysProductsServerEF sysProductsServerEF { get; set; }
        public EmployeesServerEF employeesServerEF { get; set; }
    }
    [InjectClass]
    public class SysCarShopsServer : ISysCarShopsServer
    {
        private readonly SysCarShopsEF _sysCarShopsEF;//包含所有所需仓库表实现的对象
                                                      // 请不要修改该构造方法,也无需添加属性，而应该在上面的EF类中添加属性和构造函数赋值语句
        public SysCarShopsServer(DbContext dbContext)
        {
            _sysCarShopsEF = new SysCarShopsEF(dbContext);
        }
        public async Task<ResponseApiDto> AddAsync(RequestSysCarShopsDto dto)
        {
            SysCarShops carShop = dto.ToCreateEntity();
            int affectedRows = 0;
            // 生成汽车店账号
            string account = Tools.Guid_1();
            string password = Tools.Guid_1();
            string salt = Tools.Guid_1();
            string shopImageNames = "";
            string certificateImageNames = "";
            await _sysCarShopsEF.sysCarShopsServerEF.ExecuteInTransactionAsync(async () =>
            {
                // 添加账号
                SysAccounts newAccount = new SysAccounts
                {
                    AAccount = account,
                    AName = account,
                    ARole = "carShop",
                    ASalt = salt,
                    APassword = Encrypt.GetMd5Hash(password + salt)
                };
                affectedRows += await _sysCarShopsEF.sysAccountsServerEF.AddAsync(newAccount);
                carShop.CsAccount = newAccount.AId;
                // 上传图片
                foreach (var item in dto.shopImages)
                {
                    if (shopImageNames.Length != 0)
                    {
                        shopImageNames += ",";
                    }
                    shopImageNames += await Tools.UploadImage(item, Tools.GetImageCarShopShopPath());
                }
                carShop.CsShopImages = shopImageNames;
                foreach (var item in dto.certificateImages)
                {
                    if (certificateImageNames.Length != 0)
                    {
                        certificateImageNames += ",";
                    }
                    certificateImageNames += await Tools.UploadImage(item, Tools.GetImageCarShopCertificatePath());
                }
                carShop.CsCertificateImages = certificateImageNames;
                // 添加汽车店
                affectedRows += await _sysCarShopsEF.sysCarShopsServerEF.AddAsync(carShop);
            }, () =>
            {
                //删除图片
                foreach (var item in shopImageNames.Split(","))
                {
                    Tools.DeleteImage(Path.Combine(Tools.GetImageCarShopShopPath(), item));
                }
                foreach (var item in certificateImageNames.Split(","))
                {
                    Tools.DeleteImage(Path.Combine(Tools.GetImageCarShopCertificatePath(), item));
                }
                affectedRows = 0; return null;
            });
            return ResponseApiDto.Create(affectedRows, "添加成功", "添加失败", affectedRows > 0 ? new
            {
                account,
                password
            } : null);
        }
        public async Task<bool> Exist(string id)
        {
            return await _sysCarShopsEF.sysCarShopsServerEF.Query(d => d.CsId == id).AnyAsync();
        }
        public async Task<ResponseApiDto> ToggleIsBan(string id)
        {
            if (!await Exist(id))
            {
                return ResponseApiDto.Fail("该汽车店不存在");
            }
            int affectedRows = 0;
            await _sysCarShopsEF.sysCarShopsServerEF.ExecuteInTransactionAsync(async () => {
                var carShop = await _sysCarShopsEF.sysCarShopsServerEF.Query(d => d.CsId == id).SingleAsync();
                carShop.CsIsBan = carShop.CsIsBan == 0 ? 1 : 0;
                carShop.CsIsOpen = 0;
                var account = await _sysCarShopsEF.sysAccountsServerEF.Query(d => d.AId == carShop.CsAccount).SingleOrDefaultAsync();
                if (account!=null)
                {
                    account.AIsBan = carShop.CsIsBan;
                    affectedRows+=await _sysCarShopsEF.sysAccountsServerEF.UpdateAllProperAsync(account);
                }
                affectedRows+=await _sysCarShopsEF.sysCarShopsServerEF.UpdateAllProperAsync(carShop);
            }, () => { affectedRows = 0; return null; });
            return ResponseApiDto.Create(affectedRows);
        }
        public async Task<ResponseApiDto> ToggleIsOpen(string id)
        {
            if (!await Exist(id))
            {
                return ResponseApiDto.Fail("该汽车店不存在");
            }
            var carShop = await _sysCarShopsEF.sysCarShopsServerEF.Query(d => d.CsId == id).SingleAsync();
            carShop.CsIsOpen = carShop.CsIsOpen == 0 ? 1 : 0;
            return ResponseApiDto.Create(await _sysCarShopsEF.sysCarShopsServerEF.UpdateAllProperNotNullAsync(carShop));
        }
        public async Task<ResponseApiDto> UpdateAsync(RequestSysCarShopsDto dto)
        {
            if (!await Exist(dto.id))
            {
                return ResponseApiDto.Fail("该汽车店不存在");
            }
            return ResponseApiDto.Create(await _sysCarShopsEF.sysCarShopsServerEF.UpdateAllProperNotNullAsync(dto.ToUpdateEntity()));
        }
        public async Task<ResponseApiDto> Detail(string id)
        {
            SysCarShops carShop = await _sysCarShopsEF.sysCarShopsServerEF.Query(d => d.CsId == id).SingleOrDefaultAsync();
            var responseDto = carShop.ToResponseDto();
            responseDto.typeName = await _sysCarShopsEF.dictionarysServerEF.Query(d => d.DId == responseDto.type).Select(d => d.DValue).SingleOrDefaultAsync();
            return ResponseApiDto.Success("数据已获取", responseDto);
        }
        public async Task<ResponseApiDto> PaginationAsync(int page, int limit, string key, string field, bool? order)
        {
            int total = 0;
            List<ResponseSysCarShopsDto> data = new List<ResponseSysCarShopsDto>();
            List<SysCarShops> sysCarShopss = string.IsNullOrEmpty(field) ? await _sysCarShopsEF.sysCarShopsServerEF.Pagination1(d => key == null || d.CsName.Contains(key) || d.CsManagerName.Contains(key), false, d => d.CsCreatedAt, out total, page, limit).ToListAsync() :
                await _sysCarShopsEF.sysCarShopsServerEF.Pagination1(d => key == null || d.CsName.Contains(key) || d.CsManagerName.Contains(key), order ?? true, field, out total, page, limit).ToListAsync();
            foreach (var sysCarShops in sysCarShopss)
            {
                var responseDto = sysCarShops.ToResponseDto();
                responseDto.typeName = await _sysCarShopsEF.dictionarysServerEF.Query(d => d.DId == responseDto.type).Select(d => d.DValue).SingleOrDefaultAsync();
                data.Add(responseDto);
            }
            return ResponseApiDto.Success("数据已获取", new ResponsePaginationDto { total = total, data = data });
        }
        /// <summary>
        /// PC所有商品
        /// </summary>
        /// <returns></returns>
        public async Task<ResponseApiDto> pc_sys_products(string uid)
        {
            //获取汽车店ID
            var csid = await _sysCarShopsEF.employeesServerEF.Query(d => d.EAccountId == uid).Select(d => d.ECarShopId).SingleOrDefaultAsync();
            //获取所有类型
            var ip = await _sysCarShopsEF.sysProductsServerEF.Query(d => d.PCsId==csid).GroupBy(d=>d.PCategory).Select(d=>d.Key).ToListAsync();
            List<object>data = new List<object>();
            foreach (var group in ip)
            {
                //获取所有类型的产品id
                //var pinid = await _sysCarShopsEF.sysProductsServerEF.Query(d =>d.PCategory== group).Select(d => d.PId).ToListAsync();
                data.Add(new
                {
                    categ=group,
                    //获取所有类型的产品
                    categlist = await _sysCarShopsEF.sysProductsServerEF.Query(d => /*pinid.Contains(d.PId)&&*/d.PCategory== group).ToListAsync(),
                });
            }
            return ResponseApiDto.Success("数据已获取", data);

        }
        /// <summary>
        /// 获取当前汽车店的信息
        /// </summary>
        /// <param name="shopId"></param>
        /// <returns></returns>
        public  async Task<ResponseApiDto> Get_carshop(string uid)
        {
            var data = await _sysCarShopsEF.sysCarShopsServerEF.Query(d => d.CsAccount == uid).Select(d => new
            {
                name=d.CsName,
                open=d.CsIsOpen,
                id=d.CsId,
                county=d.CsProvince+"/"+d.CsCity+"/"+d.CsCounty,
            }).SingleOrDefaultAsync();
            return ResponseApiDto.Success("数据已获取", new ResponsePaginationDto { data = data });
        }
        public async Task<ResponseApiDto> GetCarShopByAccount(string aid)
        {
            var data = await _sysCarShopsEF.sysCarShopsServerEF.Query(d => d.CsAccount == aid).SingleOrDefaultAsync();
            if (data == null)
            {
                return ResponseApiDto.Fail("账号不存在");
            }
            return ResponseApiDto.Success("数据已获取",data.ToResponseDto());
        }
        /// <summary>
        /// PC热门商品
        /// </summary>
        /// <returns></returns>
        public async Task<ResponseApiDto> pc_sys_productsrm(string uid)
        {
            //获取汽车店ID
            var csid = await _sysCarShopsEF.employeesServerEF.Query(d => d.EAccountId == uid).Select(d => d.ECarShopId).SingleOrDefaultAsync();
            //获取所有类型
            var ip = await _sysCarShopsEF.sysProductsServerEF.Query(d => d.PCsId == csid&&d.PCategory== "sys_car_supplies").Take(3).ToListAsync();
            List<object> data = new List<object>();
            foreach (var group in ip)
            {
               
                data.Add(new
                {
                    PId=group.PId,
                    PName=group.PName,
                    PPrice=group.PPrice,
                    PStockQuantity = group.PStockQuantity,
                });
            }
            return ResponseApiDto.Success("数据已获取", data);
        }
    }
}
